const db = require('./db.js')
const md5 = require('blueimp-md5')
const moment = require('moment')

function getSql (key, val) {
	const strSql = `
		select * from users where ${key}='${val}'
	`
	return strSql
}

exports.getUserByCondition = async (key, val) => {
	const strSql = getSql(key, val)
	const [user] = await db.query(strSql)
	return user
}

exports.addUser = async (body) => {
	const strSql = `
		insert into users (username,password,email,nickname,create_time,modify_time)
		values (
			'${body.email}',
			'${md5(md5(body.password))}',
			'${body.email}',
			'${body.nickname}',
			'${moment().format('YYYY-MM-DD hh:mm:ss')}',
			'${moment().format()}'
		)
	`

	try {
		const ret = await db.query(strSql)
		return ret.insertId
	} catch(err) {
		throw err
	} 
}